<?php
Class Image_Manager {

    const max_w = 1280;
    const max_h = 720;
    const max_thumb_w=250;
    const max_thumb_h = 180;
    const quality = 80;
    
    public static function resize($file) {
        list($width, $height, $type) = getimagesize($file);
        switch ($type) {
            case IMAGETYPE_GIF:
                $source = imagecreatefromgif($file);
                $fun="imagegif";
                break;
            case IMAGETYPE_JPEG:
                $source = imagecreatefromjpeg($file);
                $fun="imagejpeg";
                break;
            case IMAGETYPE_PNG:
                $source = imagecreatefrompng($file);
                $fun="imagepng";
        }
        self::resizebyType($source,self::thumb($file),$fun,(float)$width, (float)$height,(float)self::max_thumb_w,(float)self::max_thumb_h);
        self::resizebyType($source,$file,$fun,(float)$width, (float)$height,(float)self::max_w,(float)self::max_h);
    }

    public static function thumb($file) {
        $path_parts = pathinfo($file);
        return $path_parts['dirname'].'/'.$path_parts['filename'].'_thumb.'.$path_parts['extension'];
    }

    private static function per($w,$h,$mw,$mh)
    {
        $w/=$mw;
        $h/=$mh;
        return ($w>$h)?($w>1?1/$w:1):($h>1?1/$h:1);
    }  
    
    private static function resizebyType($source,$dest,$savefun,$w,$h,$mw,$mh,$q=0)
    {
        $per=self::per($w,$h,$mw,$mh);
        $new_w=intval($per*$w);
        $new_h=intval($per*$h);
        $image = imagecreatetruecolor($new_w, $new_h);
        imagecopyresampled($image, $source, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
        $q?$savefun($image, $dest, $q):$savefun($image, $dest);
    }  
    
    
}
